from Registry import Registry
from WSJob import WSJob
import queue

class MongoJob(WSJob):
	unique = True
	collection = None
	
	def build_row(self, data):
		# TODO - throw exceptions объявите метод?
		pass
	
	def __init__(self, maxsize=0):
		super().__init__(maxsize)
		self.collection = Registry.get('mongo')[self.collection_name]
	
	def setUnique(self, unique= True):
		self.unique = unique
		
	def task_done(self, host):
		self.collection.update({'name': str(host), "getted": 1}, {"$set": {"checked": 1}});
		super().task_done()
	
	def get(self, block = True, timeout = None):
		if(self.empty()):
			self.load_data()
			
		if(self.empty()):
			raise queue.Empty
		
		return super().get(block, timeout)
	
	def load_data(self):
		data = self.collection.find({"checked": 0, "getted": 0}, limit=50)
		
		for row in data:
			self.put(row['name'])
			self.collection.update({"name": row['name']}, {"$set": {"getted": 1}});
		
		return True
		
	def load_file(self, file):
		self.collection.drop()
		
		fh = open(file)
		names = list(set(fh.readlines()))
		for name in names:
			if len(name.strip()):
				self.collection.insert(self.build_row(name))
		fh.close()
		
		self.collection.create_index('name', drop_dups=True, unique=True);
	
	# 2 метода ниже взяты с 
	# http://stackoverflow.com/questions/1581895/how-check-if-a-task-is-already-in-python-queue
	# Рецепт для уникальных задачь в очереди
	def _init(self, maxsize):
		super()._init(maxsize)
		if(self.unique): 
			self.all_items = set()

	def _put(self, item):
		if(self.unique):
			if item not in self.all_items:
				super()._put(item) 
				self.all_items.add(item)
		else:
			super()._put(item)